import java.util.*;

class Solution5 {
    //结果数组
    int[] result;
    //结果数组的下标
    int index;
    //是否成环
    boolean nocycle;
    //队列的对应关系adj(有向图)
    List<Integer>[] adj;
    //WHILE：未被探索，GRAY：正在探索，BLACK：已探索
    String[] color;

    public int[] findOrder(int numCourses, int[][] prerequisites) {

        //初始化
        result = new int[numCourses];
        index = numCourses - 1;
        nocycle = true;
        adj = new List[numCourses];
        for(int i = 0; i < numCourses; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        for(int[] p : prerequisites) {
            adj[p[1]].add(p[0]);
        }
        color = new String[numCourses];
        Arrays.fill(color, "WHITE");

        //dfs
        for(int i = 0; i < numCourses && nocycle; i++) {
            if(color[i] == "BLACK") {
                continue;
            }
            dfs(i);
        }

        if(!nocycle) {return new int[0];}
        return result;
    }

    public void dfs(int u) {
        if(!nocycle) {
            return;
        }
        if(color[u] == "WHITE") {
            color[u] = "GRAY";
            for(int v : adj[u]) {
                dfs(v);
            }
        }else if(color[u] == "GRAY") {
            nocycle = false;
            return;
        }else {
            return;
        }
      color[u] = "BLACK";  
      result[index--] = u;
    }
}